import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../utils/backup_util.dart';

class BackupScreen extends StatefulWidget {
  const BackupScreen({Key? key}) : super(key: key);

  @override
  State<BackupScreen> createState() => _BackupScreenState();
}

class _BackupScreenState extends State<BackupScreen> {
  bool _isExporting = false;
  bool _isImporting = false;
  bool _isFormatting = false;
  String _statusMessage = '';
  Map<String, dynamic>? _backupInfo;

  @override
  void initState() {
    super.initState();
    _loadBackupInfo();
  }

  Future<void> _loadBackupInfo() async {
    final info = await BackupUtil.getBackupInfo();
    setState(() {
      _backupInfo = info;
    });
  }

  Future<void> _exportData() async {
    setState(() {
      _isExporting = true;
      _statusMessage = '正在导出数据...';
    });

    try {
      final result = await BackupUtil.exportAllData();
      
      if (result.success) {
        setState(() {
          _statusMessage = '导出成功！\n文件路径: ${result.filePath}\n总计 ${result.totalItems} 项数据';
        });
        
        // 刷新备份信息
        await _loadBackupInfo();
        
        // 显示成功对话框
        if (mounted) {
          _showSuccessDialog('导出成功', '已成功导出 ${result.totalItems} 项数据到备份文件');
        }
      } else {
        setState(() {
          _statusMessage = result.errorMessage ?? '导出失败';
        });
        
        if (mounted) {
          _showErrorDialog('导出失败', result.errorMessage ?? '未知错误');
        }
      }
    } catch (e) {
      setState(() {
        _statusMessage = '导出失败: $e';
      });
      
      if (mounted) {
        _showErrorDialog('导出失败', e.toString());
      }
    } finally {
      setState(() {
        _isExporting = false;
      });
    }
  }

  Future<void> _importData() async {
    // 显示确认对话框
    final confirmed = await _showConfirmDialog(
      '确认导入',
      '导入数据将添加到现有数据中，不会覆盖现有数据。确定要继续吗？',
    );
    
    if (!confirmed) return;

    setState(() {
      _isImporting = true;
      _statusMessage = '正在导入数据...';
    });

    try {
      final result = await BackupUtil.importAllData();
      
      if (result.success) {
        setState(() {
          _statusMessage = '导入成功！\n' +
              '单词: ${result.wordsImported} 个\n' +
              '题目: ${result.questionsImported} 个\n' +
              '笔记: ${result.notesImported} 个\n' +
              '作文素材: ${result.essayMaterialsImported} 个\n' +
              '总计: ${result.totalImported} 项';
        });
        
        if (mounted) {
          _showSuccessDialog('导入成功', 
              '已成功导入 ${result.totalImported} 项数据\n\n' +
              '单词: ${result.wordsImported} 个\n' +
              '题目: ${result.questionsImported} 个\n' +
              '笔记: ${result.notesImported} 个\n' +
              '作文素材: ${result.essayMaterialsImported} 个');
        }
      } else {
        setState(() {
          _statusMessage = result.errorMessage ?? '导入失败';
        });
        
        if (mounted) {
          _showErrorDialog('导入失败', result.errorMessage ?? '未知错误');
        }
      }
    } catch (e) {
      setState(() {
        _statusMessage = '导入失败: $e';
      });
      
      if (mounted) {
        _showErrorDialog('导入失败', e.toString());
      }
    } finally {
      setState(() {
        _isImporting = false;
      });
    }
  }
  
  Future<void> _formatData() async {
    // 显示确认对话框
    final confirmed = await _showConfirmDialog(
      '确认格式化',
      '格式化将删除所有数据，包括单词记忆、题目练习、笔记、作文素材。此操作不可恢复，建议先备份数据。确定要继续吗？',
    );
    
    if (!confirmed) return;
    
    // 再次确认
    final confirmedAgain = await _showConfirmDialog(
      '再次确认',
      '此操作将永久删除所有数据且无法恢复！确定要继续吗？',
    );
    
    if (!confirmedAgain) return;

    setState(() {
      _isFormatting = true;
      _statusMessage = '正在格式化数据...';
    });

    try {
      final success = await BackupUtil.formatAllData();
      
      if (success) {
        setState(() {
          _statusMessage = '格式化成功！已删除所有数据';
        });
        
        // 刷新备份信息
        await _loadBackupInfo();
        
        if (mounted) {
          _showSuccessDialog('格式化成功', '已成功删除所有数据，包括单词记忆、题目练习、笔记、作文素材');
        }
      } else {
        setState(() {
          _statusMessage = '格式化失败';
        });
        
        if (mounted) {
          _showErrorDialog('格式化失败', '操作过程中发生错误');
        }
      }
    } catch (e) {
      setState(() {
        _statusMessage = '格式化失败: $e';
      });
      
      if (mounted) {
        _showErrorDialog('格式化失败', e.toString());
      }
    } finally {
      setState(() {
        _isFormatting = false;
      });
    }
  }

  Future<bool> _showConfirmDialog(String title, String content) async {
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title, style: const TextStyle(fontFamily: 'SimHei')),
        content: Text(content, style: const TextStyle(fontFamily: 'SimHei')),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消', style: TextStyle(fontFamily: 'SimHei')),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('确定', style: TextStyle(fontFamily: 'SimHei')),
          ),
        ],
      ),
    ) ?? false;
  }

  void _showSuccessDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            const Icon(Icons.check_circle, color: Colors.green),
            const SizedBox(width: 8),
            Text(title, style: const TextStyle(fontFamily: 'SimHei')),
          ],
        ),
        content: Text(content, style: const TextStyle(fontFamily: 'FangSong')),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定', style: TextStyle(fontFamily: 'SimHei')),
          ),
        ],
      ),
    );
  }

  void _showErrorDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            const Icon(Icons.error, color: Colors.red),
            const SizedBox(width: 8),
            Text(title, style: const TextStyle(fontFamily: 'SimHei')),
          ],
        ),
        content: Text(content, style: const TextStyle(fontFamily: 'FangSong')),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  String _formatDateTime(DateTime dateTime) {
    return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '数据备份',
          style: TextStyle(fontFamily: 'SimHei'),
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SafeArea(
        bottom: true,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
            // 备份信息卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const Icon(Icons.info_outline, color: Colors.blue),
                        const SizedBox(width: 8),
                        const Text(
                          '备份文件信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'SimHei',
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    if (_backupInfo != null) ...
                      [
                        _buildInfoRow('备份时间', _formatDateTime(_backupInfo!['backup_time'])),
                        _buildInfoRow('文件大小', _formatFileSize(_backupInfo!['file_size'])),
                        _buildInfoRow('单词数量', '${_backupInfo!['words_count']} 个'),
                        _buildInfoRow('题目数量', '${_backupInfo!['questions_count']} 个'),
                        _buildInfoRow('笔记数量', '${_backupInfo!['notes_count']} 个'),
                        _buildInfoRow('作文素材', '${_backupInfo!['essay_materials_count']} 个'),
                        const Divider(),
                        _buildInfoRow('总计数据', '${_backupInfo!['total_items']} 项', isTotal: true),
                      ]
                    else
                      const Text(
                        '暂无备份文件',
                        style: TextStyle(
                          color: Colors.grey,
                          fontFamily: 'FangSong',
                        ),
                      ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 24),
            
            // 导出按钮
            ElevatedButton.icon(
              onPressed: _isExporting || _isImporting || _isFormatting ? null : _exportData,
              icon: _isExporting 
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Icon(Icons.upload),
              label: Text(
                _isExporting ? '正在导出...' : '一键导出数据',
                style: const TextStyle(fontFamily: 'SimHei'),
              ),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 导入按钮
            ElevatedButton.icon(
              onPressed: _isExporting || _isImporting || _isFormatting ? null : _importData,
              icon: _isImporting 
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Icon(Icons.download),
              label: Text(
                _isImporting ? '正在导入...' : '一键导入数据',
                style: const TextStyle(fontFamily: 'SimHei'),
              ),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 格式化按钮
            ElevatedButton.icon(
              onPressed: _isExporting || _isImporting || _isFormatting ? null : _formatData,
              icon: _isFormatting 
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Icon(Icons.delete_forever),
              label: Text(
                _isFormatting ? '正在格式化...' : '一键格式化数据',
                style: const TextStyle(fontFamily: 'SimHei'),
              ),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
              ),
            ),
            
            const SizedBox(height: 24),
            
            // 状态信息
            if (_statusMessage.isNotEmpty)
              Card(
                color: Colors.grey[100],
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Row(
                        children: [
                          Icon(Icons.info, color: Colors.blue),
                          SizedBox(width: 8),
                          Text(
                            '操作状态',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontFamily: 'SimHei',
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(
                        _statusMessage,
                        style: const TextStyle(
                          fontSize: 14,
                          fontFamily: 'FangSong',
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            
            const SizedBox(height: 24),
            
            // 说明文字
            Card(
              color: Colors.orange[50],
              margin: const EdgeInsets.only(bottom: 24.0),
              child: const Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.lightbulb_outline, color: Colors.orange),
                        SizedBox(width: 8),
                        Text(
                          '使用说明',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.orange,
                            fontFamily: 'SimHei',
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    Text(
                      '• 导出功能会将所有数据（单词记忆、题目练习、我的笔记、我的作文素材）打包到一个备份文件中\n'
                      '• 每次导出都会覆盖原有的备份文件\n'
                      '• 导入功能会将备份文件中的数据添加到当前数据库中\n'
                      '• 导入不会删除现有数据，只会新增数据\n'
                      '• 格式化功能会删除所有数据，包括单词记忆、题目练习、笔记、作文素材\n'
                      '• 格式化操作不可恢复，请在操作前备份重要数据',
                      style: TextStyle(
                        fontSize: 13,
                        color: Colors.orange,
                        fontFamily: 'SimHei',
                      ),
                    ),
                  ],
                ),
              ),
            ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value, {bool isTotal = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
              fontSize: isTotal ? 16 : 14,
              fontFamily: 'FangSong',
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
              fontSize: isTotal ? 16 : 14,
              color: isTotal ? Colors.blue : null,
              fontFamily: 'FangSong',
            ),
          ),
        ],
      ),
    );
  }
}